<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.1.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","width":300,"display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="本篇为Java线程池ThreadPoolExecutor学习的第三篇。该篇介绍了线程池的异常处理机制及手动处理异常的几种方式（我们将按照提交任务是否有返回值分别讲解），并且额外增加了线程池的常用监控参数汇总。">
<meta property="og:type" content="article">
<meta property="og:title" content="Java线程池之ThreadPoolExecutor（三）">
<meta property="og:url" content="http://example.com/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/index.html">
<meta property="og:site_name" content="履歴の本文">
<meta property="og:description" content="本篇为Java线程池ThreadPoolExecutor学习的第三篇。该篇介绍了线程池的异常处理机制及手动处理异常的几种方式（我们将按照提交任务是否有返回值分别讲解），并且额外增加了线程池的常用监控参数汇总。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/000.png">
<meta property="og:image" content="http://example.com/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/001.png">
<meta property="og:image" content="http://example.com/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/002.png">
<meta property="og:image" content="http://example.com/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/003.png">
<meta property="og:image" content="http://example.com/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/004.png">
<meta property="og:image" content="http://example.com/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/005.png">
<meta property="og:image" content="http://example.com/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/006.png">
<meta property="article:published_time" content="2020-10-15T06:48:16.000Z">
<meta property="article:modified_time" content="2020-10-21T03:03:03.812Z">
<meta property="article:author" content="モンキーDルフィ">
<meta property="article:tag" content="线程池">
<meta property="article:tag" content="多线程">
<meta property="article:tag" content="高并发">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/000.png">

<link rel="canonical" href="http://example.com/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Java线程池之ThreadPoolExecutor（三） | 履歴の本文</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">履歴の本文</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">天下风云出我辈，一入代码岁月催</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">15</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">7</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">18</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/lufei.jpg">
      <meta itemprop="name" content="モンキーDルフィ">
      <meta itemprop="description" content="海贼王におれはなる！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="履歴の本文">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java线程池之ThreadPoolExecutor（三）
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-10-15 14:48:16" itemprop="dateCreated datePublished" datetime="2020-10-15T14:48:16+08:00">2020-10-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/" itemprop="url" rel="index"><span itemprop="name">并发编程</span></a>
                </span>
            </span>

          
            <span id="/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/" class="post-meta-item leancloud_visitors" data-flag-title="Java线程池之ThreadPoolExecutor（三）" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/" itemprop="commentCount"></span>
    </a>
  </span>
  
  
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
              <span>12k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
              <span>11 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>本篇为Java线程池ThreadPoolExecutor学习的第三篇。该篇介绍了线程池的异常处理机制及手动处理异常的几种方式（我们将按照提交任务是否有返回值分别讲解），并且额外增加了线程池的常用监控参数汇总。</p>
<a id="more"></a>

<h2 id="No-Return-Value"><a href="#No-Return-Value" class="headerlink" title="No Return Value"></a>No Return Value</h2><pre><code>execute(Runnable task)</code></pre>
<h3 id="The-Source-Code-Parsing"><a href="#The-Source-Code-Parsing" class="headerlink" title="The Source Code Parsing"></a>The Source Code Parsing</h3><p>这种方式提交任务最为简单，会直接将Runnable封装到Worker的firstTask中直接执行，具体执行处的源码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">while</span> (task != <span class="keyword">null</span> || (task = getTask()) != <span class="keyword">null</span>) &#123;</span><br><span class="line">        w.lock();</span><br><span class="line">        <span class="keyword">if</span> ((runStateAtLeast(ctl.get(), STOP) ||</span><br><span class="line">                (Thread.interrupted() &amp;&amp;</span><br><span class="line">                runStateAtLeast(ctl.get(), STOP))) &amp;&amp;</span><br><span class="line">            !wt.isInterrupted())</span><br><span class="line">            wt.interrupt();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            beforeExecute(wt, task);</span><br><span class="line">            Throwable thrown = <span class="keyword">null</span>;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                task.run(); <span class="comment">// 任务执行的地方，也是异常产生的地方</span></span><br><span class="line">            &#125; <span class="keyword">catch</span> (RuntimeException x) &#123;</span><br><span class="line">                thrown = x; <span class="keyword">throw</span> x;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Error x) &#123;</span><br><span class="line">                thrown = x; <span class="keyword">throw</span> x;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Throwable x) &#123;</span><br><span class="line">                thrown = x; <span class="keyword">throw</span> <span class="keyword">new</span> Error(x);</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                afterExecute(task, thrown);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            task = <span class="keyword">null</span>;</span><br><span class="line">            w.completedTasks++;</span><br><span class="line">            w.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    completedAbruptly = <span class="keyword">false</span>;</span><br><span class="line">&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">    processWorkerExit(w, completedAbruptly);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这段代码我们之前已经分析过，这里只关注异常的处理。我们可以看到，这里有三层异常捕获（try），但是只有最内层进行了异常的处理。这里的处理有两个操作：第一个操作将异常赋值给变量thrown，然后交给afterExecute方法去处理（afterExecute方法默认是空实现）。第二个操作将异常往上层抛。那么问题来了，外边两层try并没有捕获该异常，因此异常会继续往上抛，一直上浮到我们任务定义的地方。我们写一个Demo跑一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">5</span>, <span class="number">10</span>, <span class="number">500</span>, TimeUnit.MILLISECONDS, <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">10</span>));</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">    threadPoolExecutor.execute(() -&gt; &#123;</span><br><span class="line">        System.out.println(<span class="number">123</span> / <span class="number">0</span>); <span class="comment">// 手动制造异常</span></span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行结果如下：<br><img src="/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/000.png" alt="000"><br>可以发现每个线程都发生异常，并且将异常向上传递，直到我们在lambda表达式中定义的任务<code>System.out.println(123 / 0)</code>。</p>
<h3 id="Handle-Exeception-Manually"><a href="#Handle-Exeception-Manually" class="headerlink" title="Handle Exeception Manually"></a>Handle Exeception Manually</h3><p>上面是JVM对异常的处理，直接将异常抛给我们。如果我们不去捕获处理该异常，则直接将异常相关的堆栈信息打印到控制台。在实际应用中，我们是需要手动处理异常的，方法有三。</p>
<h4 id="try-catch"><a href="#try-catch" class="headerlink" title="try-catch"></a>try-catch</h4><p>这种方式最为直接，你JVM既然已经将异常抛给我了，我只需要捕获处理一下就好了啊。Demo如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">5</span>, <span class="number">10</span>, <span class="number">500</span>, TimeUnit.MILLISECONDS, <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">10</span>));</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">    threadPoolExecutor.execute(() -&gt; &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            System.out.println(<span class="number">123</span> / <span class="number">0</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">            System.err.println(ex); <span class="comment">// 根据自己的需求处理异常，比如记录日志......</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行结果如下：<br><img src="/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/001.png" alt="001"></p>
<h4 id="afterExecute"><a href="#afterExecute" class="headerlink" title="afterExecute"></a>afterExecute</h4><p>上面我们已经提到过，在源码的三层try中，最内层的finally调用了此方法。我们可以自定义线程池重写该方法来实现异常的手动处理。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 自定义线程池：重写afterExecute方法，实现异常处理</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> xxyl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 2020/10/15 13:42</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyThreadPoolExecutor</span> <span class="keyword">extends</span> <span class="title">ThreadPoolExecutor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MyThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize, <span class="keyword">int</span> maximumPoolSize, <span class="keyword">long</span> keepAliveTime, TimeUnit unit, BlockingQueue&lt;Runnable&gt; workQueue)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MyThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize, <span class="keyword">int</span> maximumPoolSize, <span class="keyword">long</span> keepAliveTime, TimeUnit unit, BlockingQueue&lt;Runnable&gt; workQueue, ThreadFactory threadFactory)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MyThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize, <span class="keyword">int</span> maximumPoolSize, <span class="keyword">long</span> keepAliveTime, TimeUnit unit, BlockingQueue&lt;Runnable&gt; workQueue, RejectedExecutionHandler handler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MyThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize, <span class="keyword">int</span> maximumPoolSize, <span class="keyword">long</span> keepAliveTime, TimeUnit unit, BlockingQueue&lt;Runnable&gt; workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * jdk文档示例</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> r</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> t</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">afterExecute</span><span class="params">(Runnable r, Throwable t)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.afterExecute(r, t);</span><br><span class="line">        <span class="keyword">if</span> (t == <span class="keyword">null</span> &amp;&amp; r <span class="keyword">instanceof</span> Future&lt;?&gt;) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Object o = ((Future&lt;?&gt;) r).get();</span><br><span class="line">            &#125; <span class="keyword">catch</span>(CancellationException | ExecutionException ce) &#123;</span><br><span class="line">                t = ce;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                Thread.currentThread().interrupt();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (t != <span class="keyword">null</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;执行后异常处理：&quot;</span> + t.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>测试Demo如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">MyThreadPoolExecutor myThreadPoolExecutor = <span class="keyword">new</span> MyThreadPoolExecutor(<span class="number">5</span>, <span class="number">10</span>, <span class="number">500</span>, TimeUnit.MILLISECONDS, <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">10</span>));</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">    myThreadPoolExecutor.execute(() -&gt; &#123;</span><br><span class="line">        System.out.println(<span class="number">123</span> / <span class="number">0</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行结果如下：<br><img src="/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/002.png" alt="002"><br>可以看到，finally中的afterExecute方法成功拿到了异常并进行了自己的处理，但是JVM还是会将异常向上抛出！</p>
<h4 id="uncaughtExceptionHandler"><a href="#uncaughtExceptionHandler" class="headerlink" title="uncaughtExceptionHandler"></a>uncaughtExceptionHandler</h4><p>此方法需要自定义线程工厂，其中设置线程的uncaughtExceptionHandler属性。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 基本上与线程池的默认线程工厂DefaultThreadFactory一样，只是多了设置线程的uncaughtExceptionHandler属性相关代码</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> xxyl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 2020/10/15 13:57</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyThreadFactory</span> <span class="keyword">implements</span> <span class="title">ThreadFactory</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> AtomicInteger poolNumber = <span class="keyword">new</span> AtomicInteger(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ThreadGroup group;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> AtomicInteger threadNumber = <span class="keyword">new</span> AtomicInteger(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> String namePrefix;</span><br><span class="line"></span><br><span class="line">    MyThreadFactory() &#123;</span><br><span class="line">        SecurityManager s = System.getSecurityManager();</span><br><span class="line">        group = (s != <span class="keyword">null</span>) ? s.getThreadGroup() :</span><br><span class="line">                Thread.currentThread().getThreadGroup();</span><br><span class="line">        namePrefix = <span class="string">&quot;pool-&quot;</span> +</span><br><span class="line">                poolNumber.getAndIncrement() +</span><br><span class="line">                <span class="string">&quot;-thread-&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Thread <span class="title">newThread</span><span class="params">(Runnable r)</span> </span>&#123;</span><br><span class="line">        Thread t = <span class="keyword">new</span> Thread(group, r,</span><br><span class="line">                namePrefix + threadNumber.getAndIncrement(),</span><br><span class="line">                <span class="number">0</span>);</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 给线程设置uncaughtExceptionHandler，手动处理异常</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        t.setUncaughtExceptionHandler(<span class="keyword">new</span> Thread.UncaughtExceptionHandler() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">uncaughtException</span><span class="params">(Thread t, Throwable e)</span> </span>&#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;线程工厂异常处理：&quot;</span> + e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (t.isDaemon())</span><br><span class="line">            t.setDaemon(<span class="keyword">false</span>);</span><br><span class="line">        <span class="keyword">if</span> (t.getPriority() != Thread.NORM_PRIORITY)</span><br><span class="line">            t.setPriority(Thread.NORM_PRIORITY);</span><br><span class="line">        <span class="keyword">return</span> t;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>测试Demo如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">5</span>, <span class="number">10</span>, <span class="number">500</span>, TimeUnit.MILLISECONDS, <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">10</span>), <span class="keyword">new</span> MyThreadFactory());</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">    threadPoolExecutor.execute(() -&gt; &#123;</span><br><span class="line">        System.out.println(<span class="number">123</span> / <span class="number">0</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行结果如下：<br><img src="/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/003.png" alt="003"></p>
<pre><code>总结：三种手动处理异常的方式优先级为 try-catch &gt; uncaughtExceptionHandler &gt; afterExecute（此种方式不建议用，因为JVM还是会将异常上抛）</code></pre>
<h2 id="Has-Return-Value-Future"><a href="#Has-Return-Value-Future" class="headerlink" title="Has Return Value(Future)"></a>Has Return Value(Future)</h2><pre><code>submit(Runnable task)
submit(Runnable task, T result)
submit(Callable&lt;T&gt; task)</code></pre>
<p>这三种方式有一个共同点，那就是都有返回值，类型为Future。为什么本篇我们会区分有、无返回值两种情况呢？那是因为两种情况自身对异常的处理是不同的。上面我们已经知道无返回值的情况下，JVM会直接将异常向上抛，让编程者选择处理或者不处理异常。接下来我们分析一下有返回值的情况下，异常是如何处理的。</p>
<h3 id="The-Source-Code-Parsing-1"><a href="#The-Source-Code-Parsing-1" class="headerlink" title="The Source Code Parsing"></a>The Source Code Parsing</h3><h4 id="submit"><a href="#submit" class="headerlink" title="submit"></a>submit</h4><p>我们先来看一下三种submit提交任务的源码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> Future&lt;?&gt; submit(Runnable task) &#123;</span><br><span class="line">    <span class="keyword">if</span> (task == <span class="keyword">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">    RunnableFuture&lt;Void&gt; ftask = newTaskFor(task, <span class="keyword">null</span>);</span><br><span class="line">    execute(ftask);</span><br><span class="line">    <span class="keyword">return</span> ftask;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> &lt;T&gt; <span class="function">Future&lt;T&gt; <span class="title">submit</span><span class="params">(Runnable task, T result)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (task == <span class="keyword">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">    RunnableFuture&lt;T&gt; ftask = newTaskFor(task, result);</span><br><span class="line">    execute(ftask);</span><br><span class="line">    <span class="keyword">return</span> ftask;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> &lt;T&gt; <span class="function">Future&lt;T&gt; <span class="title">submit</span><span class="params">(Callable&lt;T&gt; task)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (task == <span class="keyword">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">    RunnableFuture&lt;T&gt; ftask = newTaskFor(task);</span><br><span class="line">    execute(ftask);</span><br><span class="line">    <span class="keyword">return</span> ftask;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>三种方法有一个共同点，就是通过newTaskFot方法将任务封装成了一个RunnableFuture（实现类为FutureTask）。正如名字所示，RunnableFuture继承了Runnable接口和Future接口。Runnable自不必多说，Future是对线程异步执行结果的一个抽象。通过get方法可以获取线程的执行结果，当然get方法会使线程阻塞，直到线程执行完毕/发生异常。</p>
<h4 id="newTaskFor"><a href="#newTaskFor" class="headerlink" title="newTaskFor"></a>newTaskFor</h4><p>与提交的任务类型（Runnable、Callable）对应，该方法也有两个重载：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">protected</span> &lt;T&gt; <span class="function">RunnableFuture&lt;T&gt; <span class="title">newTaskFor</span><span class="params">(Runnable runnable, T value)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> FutureTask&lt;T&gt;(runnable, value);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">protected</span> &lt;T&gt; <span class="function">RunnableFuture&lt;T&gt; <span class="title">newTaskFor</span><span class="params">(Callable&lt;T&gt; callable)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> FutureTask&lt;T&gt;(callable);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>再往下看，实际上就是FutureTask构造方法的重载：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">FutureTask</span><span class="params">(Runnable runnable, V result)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.callable = Executors.callable(runnable, result); <span class="comment">// 将Runnable封装为Callable（实际上的实现类是RunnableAdapter）</span></span><br><span class="line">    <span class="keyword">this</span>.state = NEW;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">FutureTask</span><span class="params">(Callable&lt;V&gt; callable)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (callable == <span class="keyword">null</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">    <span class="keyword">this</span>.callable = callable;</span><br><span class="line">    <span class="keyword">this</span>.state = NEW;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到，最终都是将任务转化为Callable去执行。</p>
<h4 id="runWorker"><a href="#runWorker" class="headerlink" title="runWorker"></a>runWorker</h4><p>再回到我们熟悉的runWorker方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    beforeExecute(wt, task);</span><br><span class="line">    Throwable thrown = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        task.run(); <span class="comment">// 这里的task为FutureTask</span></span><br><span class="line">    &#125; <span class="keyword">catch</span> (RuntimeException x) &#123;</span><br><span class="line">        thrown = x; <span class="keyword">throw</span> x;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Error x) &#123;</span><br><span class="line">        thrown = x; <span class="keyword">throw</span> x;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable x) &#123;</span><br><span class="line">        thrown = x; <span class="keyword">throw</span> <span class="keyword">new</span> Error(x);</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        afterExecute(task, thrown);</span><br><span class="line">    &#125;</span><br><span class="line">&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">    task = <span class="keyword">null</span>;</span><br><span class="line">    w.completedTasks++;</span><br><span class="line">    w.unlock();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里会去执行FutureTask的run方法。</p>
<h4 id="FutureTask-run"><a href="#FutureTask-run" class="headerlink" title="FutureTask.run()"></a>FutureTask.run()</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.state == <span class="number">0</span> &amp;&amp; UNSAFE.compareAndSwapObject(<span class="keyword">this</span>, runnerOffset, (Object)<span class="keyword">null</span>, Thread.currentThread())) &#123;</span><br><span class="line">        <span class="keyword">boolean</span> var9 = <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            var9 = <span class="keyword">true</span>;</span><br><span class="line">            Callable var1 = <span class="keyword">this</span>.callable; <span class="comment">// 核心代码第一步</span></span><br><span class="line">            <span class="keyword">if</span> (var1 != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (<span class="keyword">this</span>.state == <span class="number">0</span>) &#123;</span><br><span class="line">                    Object var2;</span><br><span class="line">                    <span class="keyword">boolean</span> var3;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        var2 = var1.call(); <span class="comment">// 核心代码第二步</span></span><br><span class="line">                        var3 = <span class="keyword">true</span>;</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (Throwable var10) &#123;</span><br><span class="line">                        var2 = <span class="keyword">null</span>;</span><br><span class="line">                        var3 = <span class="keyword">false</span>;</span><br><span class="line">                        <span class="keyword">this</span>.setException(var10); <span class="comment">// 核心代码第三步</span></span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">if</span> (var3) &#123;</span><br><span class="line">                        <span class="keyword">this</span>.set(var2);</span><br><span class="line">                        var9 = <span class="keyword">false</span>;</span><br><span class="line">                    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                        var9 = <span class="keyword">false</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    var9 = <span class="keyword">false</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                var9 = <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (var9) &#123;</span><br><span class="line">                <span class="keyword">this</span>.runner = <span class="keyword">null</span>;</span><br><span class="line">                <span class="keyword">int</span> var6 = <span class="keyword">this</span>.state;</span><br><span class="line">                <span class="keyword">if</span> (var6 &gt;= <span class="number">5</span>) &#123;</span><br><span class="line">                    <span class="keyword">this</span>.handlePossibleCancellationInterrupt(var6);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">this</span>.runner = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">int</span> var12 = <span class="keyword">this</span>.state;</span><br><span class="line">        <span class="keyword">if</span> (var12 &gt;= <span class="number">5</span>) &#123;</span><br><span class="line">            <span class="keyword">this</span>.handlePossibleCancellationInterrupt(var12);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们只看关键代码，实际上就是获取之前callable任务，然后去调用其call()方法，如果发生异常，将异常赋值给FutureTask的outcome（具体请看this.setException()方法）。</p>
<h4 id="Callable-call"><a href="#Callable-call" class="headerlink" title="Callable.call()"></a>Callable.call()</h4><p>这里又会有两种情况：</p>
<ol>
<li>直接传参的Callable（匿名内部类），如下：<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Future&lt;Integer&gt; submit = threadPoolExecutor.submit(<span class="keyword">new</span> Callable&lt;Integer&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">123</span> / <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
这种情况下会直接调用call()方法，执行我们手写的逻辑。</li>
<li>由Runnable封装的Callable（实现类为RunnableAdapter），我们看下RunnableAdapter的call()方法：<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> T <span class="title">call</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    task.run(); <span class="comment">// 执行封装的Runnable的run方法</span></span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h4 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h4><p>通过上面的分析，我们得知异常在FutureTask的run()方法中被吞了（内部处理）。而当我们调用FutureTask的get()方法获取异步执行结果时，又将异常吐出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> V <span class="title">get</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException, ExecutionException </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> var1 = <span class="keyword">this</span>.state;</span><br><span class="line">    <span class="keyword">if</span> (var1 &lt;= <span class="number">1</span>) &#123;</span><br><span class="line">        var1 = <span class="keyword">this</span>.awaitDone(<span class="keyword">false</span>, <span class="number">0L</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.report(var1); <span class="comment">// 调用report()方法</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> V <span class="title">report</span><span class="params">(<span class="keyword">int</span> var1)</span> <span class="keyword">throws</span> ExecutionException </span>&#123;</span><br><span class="line">    Object var2 = <span class="keyword">this</span>.outcome;</span><br><span class="line">    <span class="keyword">if</span> (var1 == <span class="number">2</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> var2;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (var1 &gt;= <span class="number">4</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> CancellationException();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ExecutionException((Throwable)var2); <span class="comment">// 将吞掉的异常吐出</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们写一个Demo跑一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">5</span>, <span class="number">10</span>, <span class="number">500</span>, TimeUnit.MILLISECONDS, <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">10</span>));</span><br><span class="line">Future&lt;Integer&gt; submit = threadPoolExecutor.submit(<span class="keyword">new</span> Callable&lt;Integer&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">123</span> / <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">submit.get();</span><br></pre></td></tr></table></figure>
<p>执行结果如下：<br><img src="/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/004.png" alt="004"></p>
<h3 id="Handle-Exeception-Manually-1"><a href="#Handle-Exeception-Manually-1" class="headerlink" title="Handle Exeception Manually"></a>Handle Exeception Manually</h3><p>现在我们知道调用get方法获取异步执行结果时有可能发生异常，实际应用中我们还是需要手动去处理该异常，方法有二。</p>
<h4 id="try-catch-1"><a href="#try-catch-1" class="headerlink" title="try-catch"></a>try-catch</h4><p>不多哔哔，简单粗糙、直接有效：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">5</span>, <span class="number">10</span>, <span class="number">500</span>, TimeUnit.MILLISECONDS, <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">10</span>));</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">    Future&lt;Integer&gt; submit = threadPoolExecutor.submit(<span class="keyword">new</span> Callable&lt;Integer&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="number">123</span> / <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        submit.get();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">        System.err.println(ex);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行结果如下：<br><img src="/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/005.png" alt="005"></p>
<h4 id="afterExecute-1"><a href="#afterExecute-1" class="headerlink" title="afterExecute"></a>afterExecute</h4><p>同样地，我们也可以通过自定义线程池重写afterExecute()方法来手动实现异常的处理（这里的自定义线程池代码与上面的一样，不再罗列）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">MyThreadPoolExecutor myThreadPoolExecutor = <span class="keyword">new</span> MyThreadPoolExecutor(<span class="number">5</span>, <span class="number">10</span>, <span class="number">500</span>, TimeUnit.MILLISECONDS, <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">10</span>));</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">    Future&lt;Integer&gt; submit = myThreadPoolExecutor.submit(<span class="keyword">new</span> Callable&lt;Integer&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="number">123</span> / <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行结果如下：<br><img src="/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/006.png" alt="006"></p>
<pre><code>总结：如果不需要使用get()方法获取异步执行结果的话，推荐使用afterExecute的方式处理异常；相反推荐使用try-catch的方式。</code></pre>
<h2 id="Thread-Pool-Monitor"><a href="#Thread-Pool-Monitor" class="headerlink" title="Thread Pool Monitor"></a>Thread Pool Monitor</h2><p>这里额外添加一个很有用的知识点————线程池的监控参数：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printThreadPoolInfo</span><span class="params">(ThreadPoolExecutor threadPoolExecutor)</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;:::::::::::::::线程池监控start:::::::::::::::&quot;</span>);</span><br><span class="line">    System.out.println(<span class="string">&quot;核心线程数：&quot;</span> + threadPoolExecutor.getCorePoolSize());</span><br><span class="line">    System.out.println(<span class="string">&quot;最大线程数：&quot;</span> + threadPoolExecutor.getMaximumPoolSize());</span><br><span class="line">    System.out.println(<span class="string">&quot;最大空闲时间：&quot;</span> + threadPoolExecutor.getKeepAliveTime(TimeUnit.MILLISECONDS) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line">    System.out.println(<span class="string">&quot;阻塞队列：&quot;</span> + threadPoolExecutor.getQueue());</span><br><span class="line">    System.out.println(<span class="string">&quot;拒绝策列：&quot;</span> + threadPoolExecutor.getRejectedExecutionHandler());</span><br><span class="line">    System.out.println(<span class="string">&quot;线程工厂：&quot;</span> + threadPoolExecutor.getThreadFactory());</span><br><span class="line">    System.out.println(<span class="string">&quot;已提交任务数：&quot;</span> + threadPoolExecutor.getTaskCount()); <span class="comment">// 提交的任务数量</span></span><br><span class="line">    System.out.println(<span class="string">&quot;正在执行任务数：&quot;</span> + threadPoolExecutor.getActiveCount()); <span class="comment">// 正在执行的任务数</span></span><br><span class="line">    System.out.println(<span class="string">&quot;已完成任务数：&quot;</span> + threadPoolExecutor.getCompletedTaskCount()); <span class="comment">// 已完成的任务数（包括异常退出的）</span></span><br><span class="line">    System.out.println(<span class="string">&quot;使用线程峰值：&quot;</span> + threadPoolExecutor.getLargestPoolSize()); <span class="comment">// 同时间使用的最高线程数</span></span><br><span class="line">    System.out.println(<span class="string">&quot;:::::::::::::::线程池监控end:::::::::::::::&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/%E7%BA%BF%E7%A8%8B%E6%B1%A0/" rel="tag"><i class="fa fa-tag"></i> 线程池</a>
              <a href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" rel="tag"><i class="fa fa-tag"></i> 多线程</a>
              <a href="/tags/%E9%AB%98%E5%B9%B6%E5%8F%91/" rel="tag"><i class="fa fa-tag"></i> 高并发</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/10/08/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor2/" rel="prev" title="Java线程池之ThreadPoolExecutor（二）">
      <i class="fa fa-chevron-left"></i> Java线程池之ThreadPoolExecutor（二）
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/10/21/gRPC%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%B8%80%EF%BC%89%E2%80%94%E2%80%94gRPC%E5%88%9D%E5%A7%8B/" rel="next" title="gRPC学习（一）——gRPC初始">
      gRPC学习（一）——gRPC初始 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#No-Return-Value"><span class="nav-number">1.</span> <span class="nav-text">No Return Value</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#The-Source-Code-Parsing"><span class="nav-number">1.1.</span> <span class="nav-text">The Source Code Parsing</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Handle-Exeception-Manually"><span class="nav-number">1.2.</span> <span class="nav-text">Handle Exeception Manually</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#try-catch"><span class="nav-number">1.2.1.</span> <span class="nav-text">try-catch</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#afterExecute"><span class="nav-number">1.2.2.</span> <span class="nav-text">afterExecute</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#uncaughtExceptionHandler"><span class="nav-number">1.2.3.</span> <span class="nav-text">uncaughtExceptionHandler</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Has-Return-Value-Future"><span class="nav-number">2.</span> <span class="nav-text">Has Return Value(Future)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#The-Source-Code-Parsing-1"><span class="nav-number">2.1.</span> <span class="nav-text">The Source Code Parsing</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#submit"><span class="nav-number">2.1.1.</span> <span class="nav-text">submit</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#newTaskFor"><span class="nav-number">2.1.2.</span> <span class="nav-text">newTaskFor</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#runWorker"><span class="nav-number">2.1.3.</span> <span class="nav-text">runWorker</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#FutureTask-run"><span class="nav-number">2.1.4.</span> <span class="nav-text">FutureTask.run()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Callable-call"><span class="nav-number">2.1.5.</span> <span class="nav-text">Callable.call()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Conclusion"><span class="nav-number">2.1.6.</span> <span class="nav-text">Conclusion</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Handle-Exeception-Manually-1"><span class="nav-number">2.2.</span> <span class="nav-text">Handle Exeception Manually</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#try-catch-1"><span class="nav-number">2.2.1.</span> <span class="nav-text">try-catch</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#afterExecute-1"><span class="nav-number">2.2.2.</span> <span class="nav-text">afterExecute</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Thread-Pool-Monitor"><span class="nav-number">3.</span> <span class="nav-text">Thread Pool Monitor</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="モンキーDルフィ"
      src="/images/lufei.jpg">
  <p class="site-author-name" itemprop="name">モンキーDルフィ</p>
  <div class="site-description" itemprop="description">海贼王におれはなる！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">18</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>
      <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=174419&auto=1&height=66"></iframe>
    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">モンキーDルフィ</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">66k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">1:01</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'rp9eaSA9Y6vBrWUdOf5ukLYs-gzGzoHsz',
      appKey     : 'SIkchhA5LF0xmXpXKtbkA65H',
      placeholder: "欢迎大家前来交流~",
      avatar     : '/images/lufei.jpg',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-CN' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
